<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/index.js'
import { changePasswordService, logoutService } from '@/api/user.js'

const router = useRouter()
const userStore = useUserStore()

// 获取当前登录用户信息
const currentUser = computed(() => userStore.user || {})

// 计算用户名首字（用于头像显示）
const userInitial = computed(() => {
  const name = currentUser.value.username || '用户'
  return name.charAt(0)
})

// 计算用户角色显示名称
const userRoleDisplay = computed(() => {
  const role = currentUser.value.role
  if (role) return role
  // 根据权限等级显示角色
  const authType = currentUser.value.authType
  if (authType === 4) return '财务管理员'
  if (authType === 3) return '人事管理员'
  if (authType === 2) return '审批经理'
  return '员工'
})

/**
 * 个人中心模态框的显示状态
 * @type {Ref<boolean>}
 */
const showProfile = ref(false)
/**
 * 弹窗当前显示的面板类型：profile（个人中心）/ resetPwd（修改密码）
 * @type {Ref<string>}
 */
const currentPanel = ref('profile')
/**
 * 修改密码表单数据
 * @type {Reactive<Object>}
 */
const pwdForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})
/**
 * 表单校验错误信息
 * @type {Ref<Object>}
 */
const pwdErrors = ref({})

/**
 * 切换个人中心模态框的显示/隐藏状态
 */
const toggleProfile = () => {
  showProfile.value = !showProfile.value
  // 关闭弹窗时重置状态：回到个人中心面板 + 清空表单和错误
  if (!showProfile.value) {
    currentPanel.value = 'profile'
    Object.keys(pwdForm).forEach(key => pwdForm[key] = '')
    pwdErrors.value = {}
  }
}

/**
 * 切换到修改密码面板
 */
const goToResetPwd = () => {
  currentPanel.value = 'resetPwd'
}

/**
 * 切换回个人中心面板
 */
const goBackToProfile = () => {
  currentPanel.value = 'profile'
  // 重置密码表单和错误
  Object.keys(pwdForm).forEach(key => pwdForm[key] = '')
  pwdErrors.value = {}
}

/**
 * 校验密码表单
 * @returns {boolean} 是否通过校验
 */
const validatePwdForm = () => {
  const errors = {}
  // 校验原密码
  if (!pwdForm.oldPassword) {
    errors.oldPassword = '请输入原密码'
  }
  // 校验新密码（长度≥6位）
  if (!pwdForm.newPassword) {
    errors.newPassword = '请输入新密码'
  } else if (pwdForm.newPassword.length < 6) {
    errors.newPassword = '新密码长度不能少于6位'
  }
  // 校验确认密码
  if (!pwdForm.confirmPassword) {
    errors.confirmPassword = '请确认新密码'
  } else if (pwdForm.confirmPassword !== pwdForm.newPassword) {
    errors.confirmPassword = '两次输入的密码不一致'
  }
  // 保存错误信息
  pwdErrors.value = errors
  // 无错误则校验通过
  return Object.keys(errors).length === 0
}

/**
 * 提交修改密码
 */
const submitResetPwd = async () => {
  // 先校验表单
  if (!validatePwdForm()) return

  try {
    const passwordData = {
      userId: currentUser.value.userId,
      username: currentUser.value.username,
      oldPassword: pwdForm.oldPassword,
      newPassword: pwdForm.newPassword
    }
    
    const response = await changePasswordService(passwordData)
    
    if (response.data.code === 1) {
      ElMessage.success('密码修改成功！请重新登录')
      // 密码修改成功后：清除token并跳转到登录页
      userStore.removeToken()
      userStore.setUser({})
      toggleProfile()
      setTimeout(() => {
        router.replace('/')
      }, 1000)
    } else {
      ElMessage.error(response.data.msg || '密码修改失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error(error.response?.data?.msg || '密码修改失败，请稍后再试')
  }
}

/**
 * 退出登录功能
 */
const logout = async () => {
  if (confirm('确定要退出登录吗？')) {
    try {
      // 调用退出登录接口
      await logoutService()
    } catch (error) {
      console.error('退出登录接口调用失败:', error)
    } finally {
      // 无论接口是否成功，都清除本地数据并跳转
      userStore.removeToken()
      userStore.setUser({})
      ElMessage.success('已退出登录')
      toggleProfile()
      router.replace('/')
    }
  }
}

// 组件挂载时获取用户信息（如果store中没有）
onMounted(async () => {
  if (!currentUser.value.username && userStore.token) {
    try {
      await userStore.getUser()
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }
})
</script>

<template>
  <header class="topbar">
    <div class="topbar-left">
      <h1 class="system-title">差旅审核系统</h1>
    </div>

    <div class="topbar-right">
      <span class="username">{{ currentUser.username || '用户' }}</span>
      <!-- 可点击的用户头像 -->
      <div class="user-avatar" @click="toggleProfile">
        <span class="avatar-text">{{ userInitial }}</span>
      </div>
    </div>
  </header>

  <!-- 个人中心模态框 -->
  <Teleport to="body">
    <!-- 使用 v-if 控制显示，点击遮罩层可关闭 -->
    <Transition name="modal-fade">
      <div v-if="showProfile" class="profile-modal" @click.self="toggleProfile">
        <div class="profile-content">
          <!-- 个人中心面板 -->
          <div v-if="currentPanel === 'profile'">
            <div class="profile-header">
              <h3>个人中心</h3>
              <button class="close-btn" @click="toggleProfile">&times;</button>
            </div>
            <div class="profile-body">
              <div class="profile-avatar-large">
                <span class="avatar-text">{{ userInitial }}</span>
              </div>
              <div class="profile-info">
                <h4>{{ currentUser.username || '用户' }}</h4>
                <p>部门：{{ currentUser.department || '未设置' }}</p>
                <p>角色：{{ userRoleDisplay }}</p>
                <p v-if="currentUser.email">邮箱：{{ currentUser.email }}</p>
                <p v-if="currentUser.phone">手机：{{ currentUser.phone }}</p>
              </div>
              <div class="profile-actions">
                <button class="profile-btn" @click="goToResetPwd">修改密码</button>
                <button class="profile-btn logout" @click="logout">退出登录</button>
              </div>
            </div>
          </div>

          <!-- 修改密码面板 -->
          <div v-else-if="currentPanel === 'resetPwd'">
            <div class="profile-header">
              <h3>修改密码</h3>
              <button class="close-btn" @click="toggleProfile">&times;</button>
            </div>
            <div class="profile-body">
              <form class="pwd-form" @submit.prevent="submitResetPwd">
                <!-- 原密码 -->
                <div class="form-group">
                  <label for="oldPassword">原密码</label>
                  <input
                    type="password"
                    id="oldPassword"
                    v-model="pwdForm.oldPassword"
                    class="form-input"
                    placeholder="请输入原密码"
                  >
                  <span class="error-text" v-if="pwdErrors.oldPassword">{{
                      pwdErrors.oldPassword
                    }}</span>
                </div>

                <!-- 新密码 -->
                <div class="form-group">
                  <label for="newPassword">新密码</label>
                  <input
                    type="password"
                    id="newPassword"
                    v-model="pwdForm.newPassword"
                    class="form-input"
                    placeholder="请输入新密码（至少6位）"
                  >
                  <span class="error-text" v-if="pwdErrors.newPassword">{{
                      pwdErrors.newPassword
                    }}</span>
                </div>

                <!-- 确认新密码 -->
                <div class="form-group">
                  <label for="confirmPassword">确认新密码</label>
                  <input
                    type="password"
                    id="confirmPassword"
                    v-model="pwdForm.confirmPassword"
                    class="form-input"
                    placeholder="请再次输入新密码"
                  >
                  <span class="error-text"
                        v-if="pwdErrors.confirmPassword">{{ pwdErrors.confirmPassword }}</span>
                </div>

                <!-- 操作按钮 -->
                <div class="form-actions">
                  <button type="button" class="profile-btn cancel-btn" @click="goBackToProfile">
                    取消
                  </button>
                  <button type="submit" class="profile-btn save-btn">确认修改</button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </Transition>
  </Teleport>
</template>

<style scoped>
/* --- 顶栏样式 --- */
.topbar {
  position: fixed; /* 固定在页面顶部 */
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  padding: 0 30px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  z-index: 999; /* 确保在大部分内容之上，但低于最高级的遮罩层 */
}

.topbar-left .system-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.topbar-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.username {
  font-size: 15px;
  color: #555;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.user-avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.avatar-text {
  color: white;
  font-weight: 600;
  font-size: 16px;
}

/* --- 个人中心模态框样式 --- */
.profile-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000; /* 高于顶栏 */
}

.profile-content {
  background: #fff;
  padding: 0;
  border-radius: 12px;
  width: 400px;
  box-shadow: 0 5px 25px rgba(0, 0, 0, 0.2);
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  border-bottom: 1px solid #e8e8e8;
}

.profile-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #aaa;
  cursor: pointer;
  line-height: 1;
  padding: 0;
  width: 30px;
  height: 30px;
}

.close-btn:hover {
  color: #333;
}

.profile-body {
  padding: 30px;
  text-align: center;
}

.profile-avatar-large {
  width: 90px;
  height: 90px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 20px;
}

.profile-avatar-large .avatar-text {
  color: white;
  font-weight: 600;
  font-size: 36px;
}

.profile-info h4 {
  margin: 0 0 10px 0;
  font-size: 20px;
  color: #333;
}

.profile-info p {
  margin: 5px 0;
  color: #666;
  font-size: 14px;
}

.profile-actions {
  margin-top: 30px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.profile-btn {
  padding: 12px 20px;
  border: 1px solid #d9d9d9;
  background: #fff;
  border-radius: 8px;
  cursor: pointer;
  font-size: 15px;
  transition: all 0.3s ease;
}

.profile-btn:hover {
  background-color: #f5f5f5;
  border-color: #667eea;
  color: #667eea;
}

.profile-btn.logout {
  color: #e74c3c;
  border-color: #f8d7da;
}

.profile-btn.logout:hover {
  background-color: #f8d7da;
  border-color: #e74c3c;
}

/* --- 修改密码表单样式 --- */
.pwd-form {
  width: 100%;
  text-align: left;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.form-input {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

.error-text {
  display: block;
  margin-top: 4px;
  font-size: 12px;
  color: #ff4d4f;
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 30px;
}

.form-actions .profile-btn {
  flex: 1; /* 按钮平分宽度 */
}

.cancel-btn:hover {
  border-color: #999;
  color: #333;
  background-color: #fafafa;
}

.save-btn {
  background: #667eea;
  color: white;
  border-color: #667eea;
}

.save-btn:hover {
  background: #7688e8;
  border-color: #7688e8;
  color: white;
}

/* --- 模态框过渡动画 --- */
.modal-fade-enter-active,
.modal-fade-leave-active {
  transition: opacity 0.3s ease;
}

.modal-fade-enter-from,
.modal-fade-leave-to {
  opacity: 0;
}
</style>
